package com.easy.admin.system.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.easy.admin.system.annon.FormToken;
import com.easy.admin.system.comnon.HttpClient;
import com.easy.admin.system.comnon.SHA1;
import com.easy.admin.system.comnon.UUIDUtil;
import com.easy.admin.system.comnon.Util;
import com.easy.admin.system.dao.MenueMapper;
import com.easy.admin.system.model.Menue;
import com.easy.admin.system.model.MenueExample;
import com.easy.admin.system.websocket.WebSocketServer;
import com.easy.admin.system.weixin.*;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.logging.log4j.core.util.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.easy.admin.system.dao.MainDao;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/main")
public class MainController {
	@Autowired
	private MainDao mainDao;
	@Autowired
	private WebSocketServer webSocketServer;
	@Autowired
	private MenueMapper menueMapper;
	/**
	 * 跳转到首页
	 * @return
	 */
	@RequestMapping("")
	@FormToken(name="index",saveToken = false)
	public String index(Model model){
		/*List<Map<String, Object>> menuss = mainDao.selectMenue();
		model.addAttribute("menues",menuss);
		Menue menue = new Menue();
		menue.setId(UUIDUtil.get32UUIDIsLowerCase());
		menue.setName("系统配置信息");
		menueMapper.insertSelective(menue);
		MenueExample menueExample = new MenueExample();
		MenueExample.Criteria c = menueExample.createCriteria();
		menueExample.setOrderByClause("pid desc");
		c.andPidIsNotNull();
		int n = menueMapper.countByExample(menueExample);
		System.out.println(n);*/
		return "index";
	}

	/**
	 * 修改个人资料页面
	 * @return
	 */
	@RequestMapping("/getMenue")
	public String getMenue(){

		//TODO 信息回显
		return "/user/Userinfo";
	}

	//微信授权认证
    @RequestMapping("/weixin")
    @ResponseBody
    public String wexi(HttpServletRequest request){
	    Map map = request.getParameterMap();
	    String signature = request.getParameter("signature");
	    String echostr = request.getParameter("echostr");
	    String timestamp = request.getParameter("timestamp");
	    String nonce = request.getParameter("nonce");
	    String token = "weixin";
	    String[] arr = {token,timestamp,nonce};
        Arrays.sort(arr);
        try {
            MessageDigest md = MessageDigest.getInstance("SHA1");
            StringBuffer buu = new StringBuffer();
            for(String st:arr){
                buu.append(st);
            }
         String opresult = SHA1.encode(buu.toString());
           if(opresult.equals(signature)){
               return echostr;
           }
        }catch(Exception e){
            e.printStackTrace();
        }

	    return "";
    }

    @ResponseBody
	@RequestMapping("/getAccessToken")
    public String getAccessToken () throws Exception{
		HttpClient cil = new HttpClient("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx38b98533eb56f567&secret=10284d04e3479f75bfeebdbffb29889c");
		cil.setHttps(true);
		cil.get();
		String content = cil.getContent();
		return content;
		/**
		 * {"access_token":"27_WaLT5frfkrQVYdeSM0M0gol79nW2DKvg4Cwi-UldEgjIxTYW5D1rUt0OdoZV24t88MNpCUXYzfVUD8z4UwwH696iuVxj01KCTufMbzkmLfXTy6Zv1DQBp47_dScLRCaAAAQWH","expires_in":7200}
		 */
    }
    @RequestMapping("/createMenu")
	@ResponseBody
    public String createMenu() throws Exception{
		Menu menu = initMenu();
		String menuStr = JSON.toJSONString(menu);
		HttpClient cilent = new HttpClient("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=27_WaLT5frfkrQVYdeSM0M0gol79nW2DKvg4Cwi-UldEgjIxTYW5D1rUt0OdoZV24t88MNpCUXYzfVUD8z4UwwH696iuVxj01KCTufMbzkmLfXTy6Zv1DQBp47_dScLRCaAAAQWH");
		cilent.setHttps(true);
		cilent.setXmlParam(JSON.toJSONString(menu));
		cilent.post();
		//int n = WeiXinUtil.createMenu(menuStr,"https://api.weixin.qq.com/cgi-bin/menu/create?access_token=27_WaLT5frfkrQVYdeSM0M0gol79nW2DKvg4Cwi-UldEgjIxTYW5D1rUt0OdoZV24t88MNpCUXYzfVUD8z4UwwH696iuVxj01KCTufMbzkmLfXTy6Zv1DQBp47_dScLRCaAAAQWH","");
		return cilent.getContent();
	}


	public static Menu initMenu() throws UnsupportedEncodingException {

		Menu menu = new Menu();

		ClickButton button11 = new ClickButton();

		button11.setName("了解杰瑞教育");

		button11.setType("click");

		button11.setKey("11");



		ClickButton button12 = new ClickButton();

		button12.setName("加入杰瑞教育");

		button12.setType("click");

		button12.setKey("12");



		ViewButton button21 = new ViewButton();

		button21.setName("杰瑞教育官网");

		button21.setType("view");

		button21.setUrl("http://www.jerehedu.com");



		ViewButton button22 = new ViewButton();

		button22.setName("杰瑞教育新闻网");

		button22.setType("view");
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx38b98533eb56f567&redirect_uri=http%3A%2F%2Fnba.bluewebgame.com%2Foauth_response.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
String redirtUrl = URLEncoder.encode("http://bo.free.idcfengye.com/EasyAdmin/main","utf-8");
	System.out.println(redirtUrl);
		button22.setUrl("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx38b98533eb56f567&redirect_uri="+redirtUrl+"&response_type=code&scope=snsapi_userinfo&state=1&connect_redirect=1#wechat_redirect");
	System.out.println(button22.getUrl());


		ClickButton button31 = new ClickButton();

		button31.setName("杰小瑞");

		button31.setType("click");

		button31.setKey("31");



		Button button1 = new Button();

		button1.setName("杰瑞教育"); //将11/12两个button作为二级菜单封装第一个一级菜单

		button1.setSub_button(new Button[]{button11,button12});



		Button button2 = new Button();

		button2.setName("相关网址"); //将21/22两个button作为二级菜单封装第二个二级菜单

		button2.setSub_button(new Button[]{button21,button22});



		menu.setButton(new Button[]{button1,button2});// 将31Button直接作为一级菜单

		return menu;

	}

	//根据当前IP或者当前url查询当前所在城市的天气
	@ResponseBody
	@RequestMapping("/getWether")
	public Object getWether(HttpServletRequest request){
		try {
			HttpClient client = new HttpClient("https://api.map.baidu.com/location/ip");
			client.setHttps(true);
			String ip = Util.getIpAddr(request);
			Map param = new HashMap();
			param.put("ip", ip);
			param.put("ak", "09Bq2j6arcn2tzwuG71mkfNxsCEvBZKy");
			param.put("coor", "bd09ll");
			client.setParameter(param);
			client.post();
			String content =client.getContent();
			return content;
		}catch (Exception e){
			e.printStackTrace();
			return null;
		}
	}

	public static void main(String[] args) {
		try {
			HttpClient client = new HttpClient("https://api.map.baidu.com/location/ip");
			client.setHttps(true);
			String ip = "61.178.41.254";
			Map param = new HashMap();
			param.put("ip", ip);
			param.put("ak", "09Bq2j6arcn2tzwuG71mkfNxsCEvBZKy");
			param.put("coor", "bd09ll");
			client.setParameter(param);
			client.post();
			String content =client.getContent();
			JSONObject object = JSONObject.parseObject(content);
			System.out.println(content);
			System.out.println(object.get("address"));
			System.out.println(object.get("content"));
		}catch (Exception e){
			e.printStackTrace();
			//return null;
		}
	}
}
